//
//  DXMLUUID.m
//  DerbyStatter
//
//  Created by glenn andreas on 1/29/14.
//  Copyright (c) 2014 glenn andreas. All rights reserved.
//


#import "DXMLUUID.h"

@interface DXMLUUID()
@property (strong) NSString *defaultID;
@property (strong) NSSet *aliases;
@end
@implementation DXMLUUID
- (NSSet *) allIDs
{
    if (self.aliases.count == 0)
        return [NSSet setWithObject:self.defaultID];
    return [self.aliases setByAddingObject:self.defaultID];
}
+ (instancetype) uniqueID
{
    DXMLUUID *retval = [[self alloc] init];
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef uuidStr = CFUUIDCreateString(kCFAllocatorDefault, uuid);
    retval.defaultID = (NSString *)CFBridgingRelease(uuidStr);
    CFRelease(uuid);
    return retval;
}
- (instancetype) initWithStringValue:(NSString *)string
{
    self = [super init];
    if (self) {
        self.defaultID = string;
    }
    return self;
}
- (id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        _defaultID = [aDecoder decodeObjectForKey:@"defaultID"];
        _aliases = [aDecoder decodeObjectForKey:@"aliases"];
    }
    return self;
}
- (void) encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_defaultID forKey:@"defaultID"];
    [aCoder encodeObject:_aliases forKey:@"aliases"];
}
- (BOOL) isEqual:(id)object
{
    if ([object isKindOfClass: [DXMLUUID class]]) {
        // grab the most common one first
        return [self.defaultID isEqualToString:[object defaultID]] ||
        [self.allIDs intersectsSet:[object allIDs]];
    } else {
        return NO;
    }
}
- (NSUInteger) hash
{
    return [self.defaultID hash];
}
- (NSString *) stringValue
{
    return self.defaultID;
}
@end
